<template>
  <div>
    <el-dialog
      v-model="localVisible"
      :title="title"
      :width="width"
      :before-close="handleClose"
      v-bind="dialogAttribute"
    >
      <div v-loading="loading" element-loading-text="拼命加载中...">
        <!-- 这里可以放置你的对话框内容 -->
        <slot></slot>
        <template v-if="hasFooter">
          <div style="display: flex; justify-content: flex-end; margin-top: 10px">
            <el-button type="primary" size="small" @click="onSubmit" :loading="loading"
              >{{ submitText }}
            </el-button>
            <el-button text size="small" @click="channel">{{ cancelText }}</el-button>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export interface DialogItemProps {
  title?: string
  width?: string
  closeTips?: boolean
  submitText?: string
  cancelText?: string
  maxWidth?: string
  hasFooter?: boolean
  dialogAttribute?: any
}
</script>

<script setup lang="ts">
//----------------------------------导入区---------------------------------
import { ElMessageBox } from 'element-plus'
//----------------------------------数据区---------------------------------
//定义组件的 props
const props = withDefaults(defineProps<DialogItemProps>(), {
  title: '弹框',
  width: '20%',
  closeTips: true,
  submitText: '确定',
  cancelText: '取消',
  maxWidth: '90%',
  hasFooter: true
})
const localVisible = defineModel<boolean>('visible')
const loading = defineModel<boolean>('hasLoading')

const emit = defineEmits(['submit', 'channel'])

// ----------------------------------方法区--------------------------------
const onSubmit = () => {
  loading.value = true
  // localVisible.value = false
  emit('submit')
}

const channel = () => {
  if (props.closeTips) {
    close()
  } else {
    localVisible.value = false // 使用 localVisible 来发射关闭事件
  }
}
// 关闭对话框时的处理逻辑
const handleClose = (done: () => void) => {
  if (props.closeTips) {
    close(done)
  } else {
    done()
  }
}

const close = (done?: () => void) => {
  ElMessageBox.confirm('确定关闭该窗口?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    buttonSize: 'small',
    type: 'warning'
  })
    .then(() => {
      if (done) {
        done()
        emit('channel')
      }
      localVisible.value = false // 使用 localVisible 来发射关闭事件
    })
    .catch(() => {
      // 处理取消操作或错误
    })
}
</script>

<style scoped></style>
